package cn.itcast.service.impl;

import cn.itcast.constant.RedisConstant;
import cn.itcast.domain.CheckGroup;
import cn.itcast.domain.SetMeal;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.mapper.MobileSetmealMapper;
import cn.itcast.mapper.SetMealMapper;
import cn.itcast.service.SetMealService;
import cn.itcast.utils.QiniuUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

import java.util.List;


@Service
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private MobileSetmealMapper mobileSetmealMapper;
    @Autowired
    private JedisPool jedisPool;

    public PageResult getMealPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();
        //当前数据绑定当前线程 会拼到sql语句后面
        PageHelper.startPage(currentPage,pageSize);

        Page<CheckGroup> page = setMealMapper.findMealByCondition(queryString);
        long total = page.getTotal();
        List<CheckGroup> rows = page.getResult();

        return new PageResult(total,rows);
    }

    public void addData(Integer[] checkgroupIds, SetMeal setMeal) {
        //添加表单数据
        setMealMapper.addSetMeal(setMeal);
        int setmeal_id = setMeal.getId();
        //查找中间表的数据 获取主键id值
        for (int i = 0; i < checkgroupIds.length; i++) {
            int checkGroup_id = checkgroupIds[i];
        // 向中间表添加数据
            setMealMapper.addCombTable(setmeal_id,checkGroup_id);
        }
        //向jedis添加一个集合
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setMeal.getImg());

    }

    public void deleteSetMeal(Integer id) {
        // 再删除 group的中间表
        setMealMapper.deleteSetmeal_GroupById(id);
        //查找 setmeal 表对应的img 的编码
        String filename =setMealMapper.selectImgById(id);
        // 删除SetMeal表
        setMealMapper.deleteSetMeal(id);
        //删除云数据
        QiniuUtils.deleteFileFromQiniu(filename);
    }


}
